package cn.edu.swu.dlx.controller;


import cn.edu.swu.dlx.db.DatabaseService;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = "/addbook")
public class AddBookServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String price = request.getParameter("price");
        double priceDouble = Double.parseDouble(price);
        String memo = request.getParameter("memo");
        String publish = request.getParameter("publish");

        ServletContext context = request.getServletContext();
        DatabaseService dbservice = (DatabaseService)context.getAttribute(DatabaseService.CONTEXT_KEY);
        String insertsql = "insert into book(name, author, price, memo, publish) values('%s','%s',%f,'%s','%s')";

        try{
            dbservice.execute(String.format(insertsql, name, author, priceDouble, memo, publish));
        }catch(Exception e){
            e.printStackTrace();
        }

        response.sendRedirect("./books");
    }
}
